package com.zhuhjay.common.base.controller;

import cn.hutool.core.date.DateUtil;
import com.zhuhjay.common.base.constant.ApplicationConstant;
import com.zhuhjay.common.base.constant.TimeConstant;
import com.zhuhjay.common.base.exception.BasicBusinessException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.util.Date;

/**
 * @author ZhuHJay
 * @date 2023/2/25 22:17
 */
public class BaseController {

    /** 将前台传递过来的日期格式的字符串，自动转化为Date类型 */
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(DateUtil.parse(text,
                        TimeConstant.DATE_TIME_FORMAT,
                        TimeConstant.DATE_FORMAT,
                        TimeConstant.TIME_FORMAT)
                );
            }
        });
    }

    /**
     * 检查是否是修改超级管理员信息
     * @param userId 用户id
     */
    protected void checkUpdateAdmin(Integer userId) {
        if (ApplicationConstant.SUPER_ADMIN_ID.equals(userId)) {
            throw new BasicBusinessException("不允许操作超级管理员");
        }
    }

    /**
     * 检查是否是修改超级管理员角色信息
     * @param roleId 角色id
     */
    protected void checkUpdateAdminRole(Integer roleId) {
        if (ApplicationConstant.SUPER_ADMIN_ROLE_ID.equals(roleId)) {
            throw new BasicBusinessException("不允许操作超级管理员角色");
        }
    }

}
